import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core'
import { ActivatedRoute, Router } from '@angular/router'
import { NzMessageService } from 'ng-zorro-antd'
import * as dayjs from 'dayjs'
import { STColumn } from '@delon/abc'
import { ACLService } from '@delon/acl'
import { SettingsService } from '@delon/theme'

import { I18NService } from '@core'
import { ListBaseClass } from '@shared/classes/ListBaseClass'
import { TradeService } from './../../trade-abstract.service'
import { ISearchSchema, ISearchOption } from '@shared/interfaces/search'
import { ESearchType } from '@shared/enums'
import { EDateLimitEnum, Currency } from '@shared/interfaces/common'
import { ITradeOnlineCharge, ITradeOnlineChargeQueryParams, ChargePaidStatusMap, EChargePaidStatus } from '@shared/interfaces/trade'
import { TradeAmountMaxValue } from 'app/utils/contraints'
import { AAMSFilterInit } from '@shared/interfaces/aams'

const today = dayjs()
  .startOf('day')
  .format('YYYY-MM-DDTHH:mm:ssZ')

@Component({
  selector: 'app-trades-onlinecharge',
  templateUrl: './online-charge.component.html',
  styleUrls: ['./../../../../shared/styles/table.less', './online-charge.component.less'],
})
export class TradesOnlineChargeComponent extends ListBaseClass<ITradeOnlineCharge, ITradeOnlineChargeQueryParams>
  implements OnInit, AAMSFilterInit {
  @ViewChild('transAmt') transAmt: TemplateRef<void>
  @ViewChild('tplCurrency') tplCurrency: TemplateRef<void>
  @ViewChild('insTpl') insTpl: TemplateRef<void>
  @ViewChild('agentTpl') agentTpl: TemplateRef<void>
  @ViewChild('merchantTpl') merchantTpl: TemplateRef<void>
  @ViewChild('storeTpl') storeTpl: TemplateRef<void>

  TradeAmountMaxValue = TradeAmountMaxValue
  searchSchema: ISearchSchema[] = []
  transAmtFrom: string // 交易金额从
  transAmtTo: string // 交易金额到
  selectedCurrency: Currency
  procFlagOptions: ISearchOption[] = []
  chargePaidStatusMap = ChargePaidStatusMap

  insCode: string

  columns: STColumn[] = [
    {
      type: 'link',
      title: '收款单号',
      i18n: 'TRADE.ONLINE_CHARGE.ORDER_NUMBER',
      index: 'onlinePayOrderNum',
      className: 'text-center',
      click: this.viewDetail.bind(this),
    },
    {
      title: '创建时间',
      i18n: 'GENERAL.INFO.CREATED_AT',
      index: 'created',
      className: 'text-center',
      type: 'date',
      dateFormat: 'YYYY-MM-DD HH:mm',
    },
    {
      title: '门店名称',
      i18n: 'GENERAL.STORE.NAME',
      index: 'storeName',
      className: 'text-center',
    },
    {
      title: '商品名称',
      i18n: 'TRADE.ONLINE_CHARGE.COMMODITY',
      index: 'commodity',
      className: 'text-center',
    },
    {
      title: '交易金额',
      i18n: 'TRADE.TRANS_AMT',
      index: 'amount',
      className: 'text-center',
      render: 'amount',
    },
    {
      title: '状态',
      i18n: 'GENERAL.INFO.STATUS',
      index: 'status',
      className: 'text-center',
      render: 'status',
    },
  ]

  constructor(
    public msg: NzMessageService,
    public i18n: I18NService,
    public route: ActivatedRoute,
    public router: Router,
    public settingService: SettingsService,
    public aclService: ACLService,
    private tradeService: TradeService,
  ) {
    super(msg, i18n, route, router, settingService)
  }

  ngOnInit() {
    this.getInsCode()
    this.inStatusOptions()
    this.initSearchParams()
    this.handleSearch()
    this.initialAAMSFilter()
  }

  initialAAMSFilter() {
    this.initAcquirer()
    this.initAgent()
    this.initMerchant()
    this.initStore()
  }

  getInsCode(): void {
    this.insCode = this.settingService.user.insCode
  }

  inStatusOptions(): void {
    for (const key in this.chargePaidStatusMap) {
      const option = { label: this.trans(this.chargePaidStatusMap[key]), value: key }
      this.procFlagOptions.push(option)
    }
  }

  initSearchParams() {
    this.searchSchema = [
      {
        label: 'GENERAL.INFO.CREATED_AT',
        labelI18n: 'GENERAL.INFO.CREATED_AT',
        index: ['createdAtFrom', 'createdAtTo'],
        type: ESearchType.dateRange,
        allowClear: false,
        dateLimitType: EDateLimitEnum.Month,
        value: [today, today],
      },
      {
        label: 'TRADE.ONLINE_CHARGE.ORDER_NUMBER',
        labelI18n: 'TRADE.ONLINE_CHARGE.ORDER_NUMBER',
        index: 'onlinePayOrderNum',
        type: ESearchType.input,
        value: '',
      },
      {
        label: 'TRADE.TRANS_AMT',
        labelI18n: 'TRADE.TRANS_AMT',
        index: ['transAmtFrom', 'transAmtTo'],
        component: this.transAmt,
        customFunc: () => [this.transAmtFrom, this.transAmtTo],
      },
      {
        label: 'GENERAL.INFO.TRANSACTION_CURRENCY',
        labelI18n: 'GENERAL.INFO.TRANSACTION_CURRENCY',
        index: 'currency',
        component: this.tplCurrency,
        customFunc: () => (this.selectedCurrency ? this.selectedCurrency.code : ''),
      },
      {
        label: 'GENERAL.BIZ_LEVEL.INSTITUTION',
        labelI18n: 'GENERAL.BIZ_LEVEL.INSTITUTION',
        index: 'insCode',
        component: this.insTpl,
        customFunc: () => (this.selectedAcquirer ? this.selectedAcquirer.code : ''),
      },
      {
        label: 'GENERAL.BIZ_LEVEL.AGENT',
        labelI18n: 'GENERAL.BIZ_LEVEL.AGENT',
        index: 'agentCode',
        component: this.agentTpl,
        customFunc: () => (this.selectedGroup ? this.selectedGroup.code : ''),
      },
      {
        label: 'GENERAL.BIZ_LEVEL.MERCHANT',
        labelI18n: 'GENERAL.BIZ_LEVEL.MERCHANT',
        index: 'intMerCode',
        component: this.merchantTpl,
        customFunc: () => (this.selectedMerchant ? this.selectedMerchant.code : ''),
      },
      {
        label: 'GENERAL.BIZ_LEVEL.STORE',
        labelI18n: 'GENERAL.BIZ_LEVEL.STORE',
        index: 'intStoreCode',
        component: this.storeTpl,
        customFunc: () => (this.selectedStore ? this.selectedStore.code : ''),
      },
      {
        label: 'GENERAL.INFO.STATUS',
        labelI18n: 'GENERAL.INFO.STATUS',
        index: 'status',
        type: ESearchType.selection,
        options: this.procFlagOptions,
      },
    ]
  }

  queryTableDataWithParams(): void {
    this.loading = true
    this.tradeService.getTradeOnlineChargeWithCurrency(this.params).subscribe(
      res => {
        this.renderList(res[1])
      },
      error => {
        this.getListError(error)
      },
    )
  }

  goAdd() {
    this.router.navigate(['../new'], { relativeTo: this.route })
  }

  viewDetail(record: ITradeOnlineCharge): void {
    const orderNum = record.onlinePayOrderNum
    this.router.navigate([`../${orderNum}`], { relativeTo: this.route })
  }

  /** 交易金额校验 */
  validateTransAmt() {
    const transAmtFromVal = this.transAmtFrom as any
    const transAmtToVal = this.transAmtTo as any

    if (
      (!isNaN(transAmtFromVal) &&
        (transAmtFromVal > Number.MAX_SAFE_INTEGER || transAmtFromVal > TradeAmountMaxValue)) ||
      (!isNaN(transAmtToVal) && (transAmtToVal > Number.MAX_SAFE_INTEGER || transAmtToVal > TradeAmountMaxValue))
    ) {
      this.msg.error(`交易金额搜索最高支持${TradeAmountMaxValue}`)
      this.searchValid = false
      return
    }

    if (!isNaN(transAmtFromVal) && !isNaN(transAmtToVal) && transAmtFromVal > transAmtToVal) {
      this.msg.error('交易金额最小值不能大于最大值，请重新设定')
      this.searchValid = false
      return
    }

    this.searchValid = true
  }

  checkSearchParamsValidation(): boolean {
    const transAmtFromVal = parseInt(this.transAmtFrom, 10)
    const transAmtToVal = parseInt(this.transAmtTo, 10)

    if (!isNaN(transAmtFromVal) || !isNaN(transAmtToVal)) {
      if (!this.selectedCurrency) {
        this.msg.error(
          this.trans('VALIDATION.REQUIRED_SELECT', { name: this.trans('GENERAL.INFO.TRANSACTION_CURRENCY') }),
        )
        return false
      }
    }
    return this.searchValid
  }

  getTradeStatus(status: EChargePaidStatus): string {
    try {
      return this.trans(ChargePaidStatusMap[status])
    } catch (e) {
      return this.trans('GENERAL.INFO.NONE')
    }
  }
}
